import { Injectable } from '@nestjs/common';
import { AnimalEntity } from '../entities/animal.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Animals, Animal } from './interface';

@Injectable()
export class AnimalService {
  constructor(
    @InjectRepository(AnimalEntity)
    private readonly animalRepository: Repository<AnimalEntity>,
  ) {}

  /**
   * 新增
   */
  async createAnimal(animal: Animal): Promise<CustomResponse<string>> {
    const sql = `INSERT INTO animal_list (name, sex) VALUES ('${animal.name}', ${animal.sex});`;
    const result = await this.animalRepository.query(sql);
    if (result.affectedRows === 1) {
      return {
        code: 200,
        msg: 'success',
        data: '添加成功',
      };
    } else {
      return {
        code: 400,
        msg: 'error',
        data: '添加失败',
      };
    }
  }
  /**
   * 根据 id 删除
   */
  async dtl(id: string): Promise<CustomResponse<any>> {
    const sql = `DELETE FROM animal_list WHERE id = '${id}'`;
    const result = await this.animalRepository.query(sql);
    if (result.affectedRows === 1) {
      return {
        code: 200,
        msg: 'success',
        data: '删除成功',
      };
    } else {
      return {
        code: 400,
        msg: 'error',
        data: '删除失败',
      };
    }
  }
  /**
   * 根据 id 修改
   */
  async update(data: Animal): Promise<CustomResponse<string>> {
    const sql = `UPDATE animal_list SET name = '${data.name}', sex = '${data.sex}' WHERE id = '${data.id}'`;
    const result = await this.animalRepository.query(sql);
    if (result.affectedRows === 1) {
      return {
        code: 200,
        msg: 'success',
        data: '更新成功',
      };
    } else {
      return {
        code: 400,
        msg: 'error',
        data: '更新失败',
      };
    }
  }
  /**
   * 根据 id 查询单条数据
   */
  async searchOne(id: string): Promise<CustomResponse<any>> {
    const sql = `SELECT * FROM animal_list WHERE id = '${id}'`;
    const result = await this.animalRepository.query(sql);
    if (Array.isArray(result) && result.length > 1) {
      return {
        code: 200,
        msg: 'success',
        data: result[0],
      };
    } else {
      return {
        code: 200,
        msg: 'success',
        data: {},
      };
    }
  }
  /**
   * 查询所有数据
   */
  async searchAll(): Promise<CustomResponse<Animals>> {
    const sql = `SELECT * FROM animal_list`;
    const result = await this.animalRepository.query(sql);
    if (Array.isArray(result)) {
      return {
        code: 200,
        msg: 'success',
        data: result,
      };
    } else {
      return {
        code: 400,
        msg: 'error',
        data: [],
      };
    }
  }
}
